package com.lanxin.kh.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lanxin.kh.entity.KhCustomer;
import com.lanxin.kh.entity.KhCustomercontact;
import com.lanxin.kh.service.IKhCustomerService;
import com.lanxin.kh.service.IKhCustomercontactService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zyq
 * @since 2025-07-23
 */
@Controller
@RequestMapping("/kh/customer")
public class KhCustomerController {

    Logger logger = Logger.getLogger(KhCustomerController.class.getName());

    @Autowired
    private IKhCustomerService khCustomerService;

    @Autowired
    private IKhCustomercontactService customercontactService;


    /**
     * 列表所有客户
     */
    @Transactional(propagation= Propagation.REQUIRED)
    @RequestMapping("/listKhCustomer")
    public String listKhCustomer(Model model,
                                 @RequestParam(defaultValue = "1") Integer page,
                                 @RequestParam(defaultValue = "5") Integer pageSize,
                                 HttpServletRequest request) {

        // 1.获取所有搜索条件（补充公司性质和所属行业）
        String customerName = request.getParameter("customerName");
        String phone = request.getParameter("phone");
        String companyType = request.getParameter("companyType"); //公司性质
        String vocation = request.getParameter("vocation");       //所属行业

        // 2.构建分页参数
        Page<KhCustomer> pageParam = new Page<>(page, pageSize);

        // 3.构建查询条件（补充公司性质和所属行业）
        QueryWrapper<KhCustomer> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(customerName)) {
            queryWrapper.like("customerName", customerName);
        }
        if (StringUtils.hasText(phone)) {
            queryWrapper.like("phone", phone);
        }
        if (StringUtils.hasText(companyType)) { //公司性质查询
            queryWrapper.eq("companyType", companyType);
        }
        if (StringUtils.hasText(vocation)) { //所属行业查询
            queryWrapper.eq("vocation", vocation);
        }

        // 4.分页查询
        IPage<KhCustomer> pageInfo = khCustomerService.page(pageParam, queryWrapper);

        // 5.传递数据到前端
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("searchCustomerName", customerName);
        model.addAttribute("searchPhone", phone);
        model.addAttribute("searchCompanyType", companyType); //回显公司性质
        model.addAttribute("searchVocation", vocation);       //回显所属行业

        return "kh/listKhCustomer";
    }

    /**
     * 删除客户
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @RequestMapping("/deleteKhCustomer")
    @ResponseBody
    public boolean deleteKhCustomer(@RequestParam("oid") Integer oid) { // oid类型与实体类保持一致
        if (oid == null) {
            logger.error("删除客户失败：oid为空");
            return false;
        }

        //判断客户是否有关联联系人，有则不允许删除
        QueryWrapper<KhCustomercontact> contactQuery = new QueryWrapper<>();
        contactQuery.eq("customerid", oid);
        long contactCount = customercontactService.count(contactQuery);
        if (contactCount > 0) {
            logger.error("删除客户失败");
            return false;
        }

        // 实际业务中可添加"是否被使用"的判断
        boolean isDeleted = khCustomerService.removeById(oid);
        if (isDeleted) {
            logger.info("删除客户成功：oid=" + oid);
        } else {
            logger.error("删除客户失败：oid=" + oid);
        }
        return isDeleted;
    }


    /**
     * 去添加客户
     * @param model
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @RequestMapping("/toAddKhCustomer")
    public String toAddKhCustomer(Model model) {
        return "kh/AddKhCustomer";
    }


    /**
     * 添加客户
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping("/addKhCustomer")
    public String addKhCustomer(KhCustomer khCustomer,
                                @RequestParam("contactName") List<String> names,
                                @RequestParam("job") List<String> jobs,
                                @RequestParam("cphone") List<String> phones,
                                @RequestParam("cemail") List<String> emails,
                                @RequestParam("caddress") List<String> addresses,
                                @RequestParam("czipcode") List<String> zipcodes) {

        khCustomerService.save(khCustomer);

        if(names!=null && names.size()>0) {

            int i = 0;
            for (String name : names) {
                KhCustomercontact contact = new KhCustomercontact();
                contact.setContactName(name);
                contact.setJob(jobs.get(i));
                contact.setPhone(phones.get(i));
                contact.setEmail(emails.get(i));
                contact.setAddress(addresses.get(i));
                contact.setZipcode(zipcodes.get(i));
                contact.setCustomerid(khCustomer.getOid());

                customercontactService.save(contact);
                i++;
            }

        }

        return "redirect:/kh/customer/listKhCustomer";
    }



    /**
     * 客户详情
     */
    @RequestMapping("/khCustomerInfo")
    public String khCustomerInfo(@RequestParam Integer oid, Model model) {
        // 1. 查询客户基本信息
        KhCustomer khCustomer = khCustomerService.getById(oid);
        if (khCustomer == null) {
            logger.error("查询客户详情失败：oid=" + oid + " 不存在");
            return "redirect:/kh/customer/listKhCustomer";
        }

        // 2. 新增：查询该客户关联的所有联系人
        QueryWrapper<KhCustomercontact> contactQuery = new QueryWrapper<>();
        contactQuery.eq("customerid", oid); // 按客户ID关联
        List<KhCustomercontact> contacts = customercontactService.list(contactQuery);

        // 3. 传递数据到前端（客户信息+联系人列表）
        model.addAttribute("khCustomer", khCustomer);
        model.addAttribute("contacts", contacts); // 新增联系人列表传递

        return "kh/khCustomerInfo";
    }



    /**
     * 去修改客户信息
     */
    @RequestMapping("/toUpdateKhCustomer")
    public String toUpdateKhCustomer(@RequestParam Integer oid, Model model) {
        // ：查询客户基本信息
        KhCustomer khCustomer = khCustomerService.getById(oid);
        if (khCustomer == null) {
            return "redirect:/kh/customer/listKhCustomer";
        }

        // 查询该客户的所有联系人
        QueryWrapper<KhCustomercontact> contactQuery = new QueryWrapper<>();
        contactQuery.eq("customerid", oid);
        List<KhCustomercontact> contacts = customercontactService.list(contactQuery);

        // 传递客户+联系人数据到前端
        model.addAttribute("khCustomer", khCustomer);
        model.addAttribute("contacts", contacts); // 回显联系人

        return "kh/UpdateKhCustomer";
    }


    /**
     * 修改客户信息
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping("/updateKhCustomer")
    public String updateKhCustomer(KhCustomer khCustomer,
                                   @RequestParam(value="coid", required = false) List<Integer> coid,
                                   @RequestParam(value="contactName", required = false) List<String> names,
                                   @RequestParam(value="job", required = false) List<String> jobs,
                                   @RequestParam(value="cphone", required = false) List<String> phones,
                                   @RequestParam(value="cemail", required = false) List<String> emails,
                                   @RequestParam(value="caddress", required = false) List<String> addresses,
                                   @RequestParam(value="czipcode", required = false) List<String> zipcodes
                                   ) {
        try {
            //khCustomerService.updateById(khCustomer);

            Integer customerId = khCustomer.getOid();

            if (customerId == null) {
                logger.error("修改客户失败：客户ID为空");
                return "redirect:/kh/customer/listKhCustomer";
            }


            // 更新客户基本信息
            boolean updateCustomer = khCustomerService.updateById(khCustomer);
            if (!updateCustomer) {
                return "redirect:/kh/customer/toUpdateKhCustomer?oid=" + customerId;
            }

            // 删除该客户原有所有联系人（先清后加
//            QueryWrapper<KhCustomercontact> deleteQuery = new QueryWrapper<>();
//            deleteQuery.eq("customerid", customerId);
//            customercontactService.remove(deleteQuery);

            int i=0;
            // 保存新的联系人列表
            if (names != null && !names.isEmpty()) {
                for (String name : names) {
                    KhCustomercontact contact = new KhCustomercontact();
                    contact.setContactName(name);

                    if(coid != null && !coid.isEmpty()) {
                        contact.setOid(coid.get(i));
                    } else {
                        contact.setOid(null); // 新增附件时oid为null
                    }
                    contact.setJob(jobs.get(i));
                    contact.setPhone(phones.get(i));
                    contact.setEmail(emails.get(i));
                    contact.setAddress(addresses.get(i));
                    contact.setZipcode(zipcodes.get(i));
                    contact.setCustomerid(customerId);

                    if(contact.getOid()==null || contact.getOid().equals("")) {
                        customercontactService.save(contact);
                    }
                    else {
                        customercontactService.updateById(contact);
                    }
                    i++;
                }

            }

            return "redirect:/kh/customer/listKhCustomer";
        } catch (Exception e) {
            logger.error("修改客户+联系人失败");
            throw new RuntimeException(e); // 触发事务回滚
        }
    }

    //删除移动明细方法
//    @RequestMapping(value = "/deleteKhCustomer")
//    @ResponseBody
//    public Boolean deleteKhCustomer(@RequestParam("oids") String oids) {
//        String[] idStrs = oids.split(",");
//        List<Integer> idList = new ArrayList<>();
//        for (String idStr : idStrs) {
//            // 将字符串转换为Integer（注意处理空字符串或非数字的情况）
//            if (idStr != null && !idStr.trim().isEmpty()) {
//                idList.add(Integer.parseInt(idStr.trim()));
//            }
//        }
//        return customercontactService.removeByIds(idList);
//    }

}
